package com.studerb.tasks;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.io.DotTerminatedMessageReader;
import org.apache.commons.net.nntp.NNTPCommand;
import org.apache.commons.net.nntp.NNTPReply;
import org.springframework.beans.factory.annotation.Autowired;

import com.studerb.nntp.NntpConnection;
import com.studerb.service.NetworkMonitorService;

public class HelpTask extends AbstractTask<Void, Void> {
    @Autowired NetworkMonitorService networkMonitorService;
    String helpString;
    DotTerminatedMessageReader dotReader = null;
    int ret;
    int tempProgress = 0;

    @Override public void init() {
        logger.debug("Task Init()");
        this.title = "HelpCommand Task";
        setMessage("Waiting for Connection");
        this.determinable = true;
        this.connectionNeeded = true;
    }

    @Override protected Void doInBackground() throws Exception {
        setProgress(10);
        NntpConnection conn = this.getConnectionion();
        int ret;
            try{
                setProgress(33);
                Thread.sleep(3000);
                setProgress(50);
                setMessage("Sending HELP Command");
                ret = conn.sendCommand(NNTPCommand.HELP);
                if(ret != NNTPReply.HELP_TEXT_FOLLOWS){
                    throw new IOException("Help Command Error: " + conn.getReplyCode() + "  " + conn.getReplyString());
                }
                setMessage("Received: " + conn.getReplyString());
                dotReader = new DotTerminatedMessageReader(conn.getReader());
                helpString = IOUtils.toString(dotReader);
                logger.debug("Got Help String: " + helpString);
                setProgress(100);
            }
            finally{
                IOUtils.closeQuietly(dotReader);
            }
        return null;
    }
}
